<template>
  <div class="approval-detail-container">
    <el-card v-if="instance">
      <div slot="header">
        <span>审批详情</span>
        <el-button 
          type="text" 
          style="float: right; padding: 3px 0;"
          @click="goBack"
        >
          <i class="el-icon-back"></i> 返回
        </el-button>
      </div>
      
      <div class="detail-section">
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">标题：</span>
              <span class="value">{{ instance.title }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">流程名称：</span>
              <span class="value">{{ instance.processName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">申请人：</span>
              <span class="value">{{ instance.applicantName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">状态：</span>
              <el-tag :type="getStatusType(instance.status)">
                {{ getStatusText(instance.status) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">发起时间：</span>
              <span class="value">{{ formatDate(instance.startTime) }}</span>
            </div>
          </el-col>
          <el-col :span="12" v-if="instance.endTime">
            <div class="info-item">
              <span class="label">结束时间：</span>
              <span class="value">{{ formatDate(instance.endTime) }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <el-divider></el-divider>
      
      <div class="detail-section">
        <h3>表单内容</h3>
        <div v-if="formDataObj" class="form-data-content">
          <el-row :gutter="20">
            <el-col :span="12" v-for="(value, key) in formDataObj" :key="key">
              <div class="info-item">
                <span class="label">{{ key }}：</span>
                <span class="value">{{ value }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <el-divider></el-divider>
      
      <div class="detail-section">
        <h3>审批流程</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(task, index) in tasks"
            :key="index"
            :color="getTimelineColor(task.status)"
            :icon="getTimelineIcon(task.status)"
          >
            <div class="timeline-content">
              <div class="timeline-header">
                <span class="node-name">
                  {{ task.taskName }}
                  <el-tag v-if="task.taskType === 'parallel'" type="warning" size="mini">会签</el-tag>
                  <el-tag v-else-if="task.taskType === 'any'" type="success" size="mini">与签</el-tag>
                </span>
                <el-tag :type="getTaskStatusType(task.status)" size="small">
                  {{ getTaskStatusText(task.status) }}
                </el-tag>
              </div>
              <div class="timeline-body">
                <p><strong>审批人：</strong>{{ task.assigneeName || '待分配' }}</p>
                <p v-if="task.transferFromName">
                  <strong>转签来源：</strong>{{ task.transferFromName }}
                  <span v-if="task.transferReason">（{{ task.transferReason }}）</span>
                </p>
                <p v-if="task.comment"><strong>审批意见：</strong>{{ task.comment }}</p>
                <p v-if="task.completeTime">
                  <strong>处理时间：</strong>{{ formatDate(task.completeTime) }}
                </p>
                <p v-else>
                  <strong>到达时间：</strong>{{ formatDate(task.createTime) }}
                </p>
                <!-- 添加操作按钮 -->
                <div v-if="task.status === 'PENDING' && isMyTask(task)" class="task-actions">
                  <el-button type="primary" size="mini" @click="showApproveDialog(task)">
                    审批
                  </el-button>
                  <el-button v-if="task.canTransfer" size="mini" @click="showTransferDialog(task)">
                    转签
                  </el-button>
                </div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
    
    <!-- 审批对话框 -->
    <el-dialog title="审批" :visible.sync="approveDialog.visible" width="500px">
      <el-form :model="approveDialog.form" label-width="100px">
        <el-form-item label="审批动作">
          <el-radio-group v-model="approveDialog.form.action">
            <el-radio label="approve">同意</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input
            v-model="approveDialog.form.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="approveDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleApprove">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 转签对话框 -->
    <el-dialog title="转签" :visible.sync="transferDialog.visible" width="500px">
      <el-form :model="transferDialog.form" label-width="100px">
        <el-form-item label="转交给" required>
          <el-select v-model="transferDialog.form.targetUserId" placeholder="请选择转签人" style="width: 100%;">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
              :disabled="user.id === currentUserId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转签原因">
          <el-input
            v-model="transferDialog.form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入转签原因"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="transferDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleTransfer">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInstanceDetail, completeTask, transferTask } from '@/api/approval'
import { getUserList } from '@/api/user'

export default {
  name: 'ApprovalDetail',
  
  data() {
    return {
      instance: null,
      tasks: [],
      userList: [],
      currentUserId: null,
      approveDialog: {
        visible: false,
        currentTask: null,
        form: {
          action: 'approve',
          comment: ''
        }
      },
      transferDialog: {
        visible: false,
        currentTask: null,
        form: {
          targetUserId: null,
          reason: ''
        }
      }
    }
  },
  
  computed: {
    formDataObj() {
      if (this.instance && this.instance.formData) {
        try {
          return JSON.parse(this.instance.formData)
        } catch (e) {
          return {}
        }
      }
      return {}
    }
  },
  
  created() {
    this.loadDetail()
    this.loadUsers()
    this.currentUserId = this.$store.state.user?.id
  },
  
  methods: {
    // 智能返回
    goBack() {
      const query = this.$route.query
      
      // 如果是从审批中心来的，返回到对应的tab
      if (query.from === 'approval-center' && query.tab) {
        this.$router.push({
          path: '/approval-center',
          query: { tab: query.tab }
        })
      } else {
        // 否则使用浏览器后退
        this.$router.go(-1)
      }
    },
    
    loadDetail() {
      const id = this.$route.params.id
      getInstanceDetail(id).then(res => {
        this.instance = res.data.instance
        this.tasks = res.data.tasks
      })
    },
    
    loadUsers() {
      getUserList().then(res => {
        this.userList = res.data
      })
    },
    
    isMyTask(task) {
      return task.assigneeId === this.currentUserId
    },
    
    showApproveDialog(task) {
      this.approveDialog.currentTask = task
      this.approveDialog.form = {
        action: 'approve',
        comment: ''
      }
      this.approveDialog.visible = true
    },
    
    showTransferDialog(task) {
      this.transferDialog.currentTask = task
      this.transferDialog.form = {
        targetUserId: null,
        reason: ''
      }
      this.transferDialog.visible = true
    },
    
    handleApprove() {
      const { currentTask, form } = this.approveDialog
      if (!form.comment && form.action === 'reject') {
        this.$message.warning('拒绝时请填写审批意见')
        return
      }
      
      completeTask({
        taskId: currentTask.id,
        action: form.action,
        comment: form.comment
      }).then(() => {
        this.$message.success('审批成功')
        this.approveDialog.visible = false
        this.loadDetail()
      }).catch(() => {
        // 错误已经在request.js中统一处理，这里不需要再次提示
      })
    },
    
    handleTransfer() {
      const { currentTask, form } = this.transferDialog
      if (!form.targetUserId) {
        this.$message.warning('请选择转签人')
        return
      }
      
      transferTask(currentTask.id, form.targetUserId, form.reason || '工作需要').then(() => {
        this.$message.success('转签成功')
        this.transferDialog.visible = false
        this.loadDetail()
      }).catch(() => {
        // 错误已经在request.js中统一处理，这里不需要再次提示
      })
    },
    
    getStatusType(status) {
      const map = {
        PENDING: 'warning',
        APPROVED: 'success',
        REJECTED: 'danger',
        CANCELLED: 'info'
      }
      return map[status] || 'info'
    },
    
    getStatusText(status) {
      const map = {
        PENDING: '审批中',
        APPROVED: '已通过',
        REJECTED: '已拒绝',
        CANCELLED: '已撤销'
      }
      return map[status] || status
    },
    
    getTaskStatusType(status) {
      const map = {
        PENDING: 'warning',
        APPROVED: 'success',
        REJECTED: 'danger'
      }
      return map[status] || 'info'
    },
    
    getTaskStatusText(status) {
      const map = {
        PENDING: '待处理',
        APPROVED: '已同意',
        REJECTED: '已拒绝',
        TRANSFERRED: '已转签'
      }
      return map[status] || status
    },
    
    getTimelineColor(status) {
      const map = {
        PENDING: '#E6A23C',
        APPROVED: '#67C23A',
        REJECTED: '#F56C6C'
      }
      return map[status] || '#909399'
    },
    
    getTimelineIcon(status) {
      const map = {
        PENDING: 'el-icon-time',
        APPROVED: 'el-icon-check',
        REJECTED: 'el-icon-close'
      }
      return map[status] || 'el-icon-more'
    },
    
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.approval-detail-container {
  max-width: 1000px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 100px;
}

.info-item .value {
  color: #303133;
}

.form-data-content {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
}

.timeline-content {
  padding: 10px;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.node-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.timeline-body p {
  margin: 5px 0;
  color: #606266;
}

.task-actions {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #DCDFE6;
}
</style>

